﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UPhiGenerater
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
        }

        private void BtGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                bool isFrequency = true;
                bool israd = true;
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string fileName = textBox1.Text;
                decimal frequencyOrWaveLength = numericUpDown1.Value;
                float min = 0;
                float max = 10;
                int dataLength = 256;
                float[] testedvolArray = getArrayFromString(richTextBox1.Text);
                float[] testedphiArray = getArrayFromString(richTextBox2.Text);
                float[] volArray = new float[dataLength];
                float[] phiArray = new float[dataLength];
                float deltVol = (max - min) / (dataLength - 1);
                if(comboBox1.SelectedIndex == 0)
                {
                    //pinlv
                    isFrequency = true;
                }   
                else
                {
                    isFrequency = false;
                }
                if (comboBox2.SelectedIndex == 0)
                {
                    
                    israd = false;
                    for(int i=0;i< testedphiArray.Length; i++)
                    {
                        testedphiArray[i] =(float) (testedphiArray[i] / 180f * Math.PI);
                    }
                }
                else
                {
                    israd = true;
                }
                for (int i = 0; i < dataLength; i++)
                {
                    volArray[i] = min + deltVol * i;
                    phiArray[i] = getguessedPhi(testedvolArray, testedphiArray, volArray[i]);
                }
                if (exportVolToTXT(volArray, phiArray, frequencyOrWaveLength, fileName + date + ".txt", textBox2.Text,isFrequency))
                {
                    ShowMsg("生成成功，请检查程序所在文件夹");
                }
                else
                {
                    ShowMsg("生成失败");
                }
            }
            catch (Exception ex)
            {
                ShowMsg("生成失败,原因为"+ex.ToString());
            }
        }

        void ShowMsg(string msg)
        {
            MessageBox.Show(msg);
        }

        public float[] getArrayFromString(string s)
        {
            string[] tem = s.Split( new string[5] { "\n", "\t", "", "\r", " " }, StringSplitOptions.RemoveEmptyEntries );
            float[] res = new float[tem.Length];
            for(int i=0;i<res.Length;i++)
            {
                res[i] = (float)Convert.ToDouble(tem[i]);
            }
            return res;
        }

        /// <summary>
        /// 保存电压到TXT
        /// </summary>
        /// <param name="vol"></param>
        /// <param name="txtfile"></param>
        /// <param name="fm"></param>
        /// <returns></returns>
        public static bool exportVolToTXT(float[] vol, float[] phase, decimal frequencyOrWaveLength, string txtfile,string description,bool isFrequency)
        {
            string fileFullName = txtfile;
            List<float> volImport = new List<float>();
            FileStream fs = new FileStream(fileFullName, FileMode.Create, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.WriteLine(@";u-phi start" +"\t"+ @"//"+ description+",单位rad"+  DateTime.Now.ToString("yyyy-MM-dd"));
            if (isFrequency)
            {
                sw.WriteLine(@"U	P@频率" + frequencyOrWaveLength + "Ghz");
            }
            else
            {
                sw.WriteLine(@"U	P@波长" + frequencyOrWaveLength + "nm");
            }
            
            for (int i = 0; i < vol.Length; i++) 
            {
                sw.WriteLine(vol[i].ToString() + "\t" + phase[i].ToString());
            }
            sw.WriteLine(@";u-phi end");
            sw.Close();
            fs.Close();
            return true;
        }

        private float interpolate(float x1, float x2, float y1, float y2, float newX)
        {
            if (x1 == x2)
            {
                return y1;
            }
            float res = (y1 - y2) / (x1 - x2) * (newX - x1) + y1;
            return res;
        }

        private float getguessedPhi(float[] testedvolArray, float[] testedphiArray, float aimVol)
        {
            int[] closedIndexvol = getClosedVolIndex(testedvolArray, aimVol);
            float phi = interpolate(testedvolArray[closedIndexvol[0]], testedvolArray[closedIndexvol[1]], testedphiArray[closedIndexvol[0]], testedphiArray[closedIndexvol[1]], aimVol);
            return phi;
        }

        private int[] getClosedVolIndex(float[] testedvolArray, float aimVol)
        {
            int left = 0;
            int right = 1;
            if (testedvolArray[0] >= aimVol)
            {
                left = 0;
                right = 1;
            }
            else if (testedvolArray[testedvolArray.Length - 1] <= aimVol)
            {
                left = testedvolArray.Length - 1;
                right = testedvolArray.Length - 1;
            }
            else
            {
                for (int i = 0; i < testedvolArray.Length; i++)
                {
                    if (testedvolArray[i] - aimVol >= 0)
                    {
                        left = i - 1;
                        right = i;
                        break;
                    }
                }
            }
            return new int[2] { left, right };
        }

        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                numericUpDown1.Value =(decimal)26.96;
            }else if(comboBox1.SelectedIndex == 1)
            {
                numericUpDown1.Value = (decimal)1550;
            }
        }

        private void Label1_Click(object sender, EventArgs e)
        {

        }
    }
}
